import React, { useState } from 'react';
import { for_obj, d_sort, cline, GridTable, useCmd, WaitUmd, MainView, obj_str, PanelTitle,
    to_float, save_xlsx, obj_int, obj_str_trim, uDb, Btn, loc } from 'sui';

const GtSumView = ({ title, mod, high }) => {
    const [row, setRow] = useState();
    const umd = useCmd();

    const hcalc = () => {
        umd.startWait();

        uDb(null, `${mod}/list`, { line: cline() },
            r => {
                const ball_map = {};

                r.forEach(d => {
                    const t_dnum = obj_int(d, "dnum");
                    const t_ball = obj_str_trim(d, "ball");

                    if (t_dnum <= 0) {
                        return false;
                    }

                    if (ball_map[t_ball]) {
                        ball_map[t_ball] += t_dnum;
                    } else {
                        ball_map[t_ball] = t_dnum;
                    }
                });

                const ret = [];

                for_obj(ball_map, (k, v) => ret.push({ sn: k, num: v, ball: to_float(v) }));

                d_sort(ret, "ball");

                ret.forEach((d, i) => d["index"] = i + 1);

                setRow(ret);

                umd.endWait();
            },
            e => {
                setRow(null);
                umd.setErr();
            });
    };

    const col = [
        {name: loc("l_193"), key: 'index', width: 70},
        {name: loc("l_714"), key: 'sn', width: 100},
        {name: loc("l_127"), key: 'num', width: 100},
    ];

    const hExport = () => {
        umd.startWait();

        const col_c = [];
        const h = [];

        col.forEach(d => {
            h.push({ value: d.name });
            col_c.push(d.key);
        });

        const out = [h];

        row.forEach(d => {
            const tmp = [];
            col_c.forEach(t => tmp.push({ value: obj_str(d, t) }));

            out.push(tmp);
        });

        save_xlsx(out, `${title}_${loc("l_793")}_${loc("l_828")}.xlsx`, umd);
    };

    const Right = () => (
        <div className="inline-flex">
            <Btn color="green" hcmd={hExport} className="mr-4">{loc("l_519")}</Btn>
        </div>
    );

    const Left = () => (
        <div className="inline-flex">
            <Btn hcmd={() => hcalc()} color="teal" className="mr-4">{loc("l_332")}</Btn>
        </div>
    );

    return (
        <MainView>
            <PanelTitle left={<Left/>} right={<Right/>} cl="gray"/>
            <GridTable col={col} row={row} high={high}/>
            <WaitUmd umd={umd}/>
        </MainView>
    );
};

export {GtSumView};
